<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Post\GoodsBatchRestore;
use App\Admin\Actions\Post\GoodsRestore;
use App\Admin\Repositories\GrGood;
use App\Models\GoodsSku;
use App\Models\GoodsSpec;
use App\Models\GoodsSpecRel;
use App\Models\GoodsSpecValue;
use App\Models\GrGoodsType;
use App\service\ReviewImages;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Fsc123\Fsc\ElasticConnect;
use Illuminate\Support\Facades\Storage;

class GrGoodController extends AdminController
{

    public function __construct()
    {
        $type = GrGoodsType::where('status',1)->get()->toArray();
        $typeInfo = [];
        foreach ($type as $val) {
            $typeInfo[$val['goods_type_id']] = $val['goods_type_name'];
        }
        $this->type = $typeInfo;

    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new GrGood(['typeInfo']), function (Grid $grid) {
            // excel导出
            $grid->export();

            // 规格筛选
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->select('goods_type_id', '分类',$this->type);
                $selector->select('status', '状态', [
                    1 => '开启',
                    0 => '关闭',
                ]);
                $selector->select('goods_now_price', '价格', ['0-999', '1000-1999', '2000-2999','3000+'], function ($query, $value) {
                    $between = [
                        [0, 999],
                        [1000, 1999],
                        [2000, 2999],
                        [3000,9999999999999]
                    ];

                    $value = current($value);

                    $query->whereBetween('goods_now_price', $between[$value]);
                });



            });
            // 回收站入口
            $grid->filter(function ($filter) {
                // 范围过滤器，调用模型的`onlyTrashed`方法，查询出被软删除的数据。
                $filter->scope('trashed', '回收站')->onlyTrashed();

            });

            // 恢复单条数据
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (request('_scope_') == 'trashed') {
                    $actions->append(new GoodsRestore(\App\Models\GrGood::class));
                }
            });
            // 批量恢复数据
            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                if (request('_scope_') == 'trashed') {
                    $batch->add(new GoodsBatchRestore(\App\Models\GrGood::class));
                }
            });

            $grid->column('goods_id', '商品ID')->sortable();
            $grid->column('typeInfo.goods_type_name', '所属分类');
            $grid->column('goods_name');
            $grid->column('goods_img_cover')->image();
            $grid->column('goods_now_price');
            $grid->column('stock_total');
            $grid->column('sales_actual');
            $grid->column('status')->switch('', true);
            $grid->column('sort');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('goods_id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new GrGood(['typeInfo']), function (Show $show) {
            $show->field('goods_id','商品ID');
            $info=$this->type;
            $show->field('goods_type_id','所属分类')->as(function ($type) use ($info){
                return $info["$type"];
            });
            $show->field('goods_name');
            $show->field('goods_no');
            $show->field('goods_video')->unescape()->as(function ($avatar) {

                return "<video src='http://llj.sunqi.ink/{$avatar}' controls='controls' style='width: 200px;height: 500px;'></video>";

            });
            $show->field('goods_img')->image();
            $show->field('goods_img_cover')->image();
            $show->field('selling_point');
            $show->field('spec_type')->as(function ($content) {
                if ($content==2){
                    return "多规格";
                }else{
                    return "单规格";
                }

            });
            $show->field('goods_now_price');
            $show->field('goods_price_min');
            $show->field('goods_price_max');
            $show->field('line_price_min');
            $show->field('line_price_max');
            $show->field('stock_total');
            $show->field('deduct_stock_type');
            $show->field('content')->unescape()->as(function ($avatar) {

                return "{$avatar}";

            });
            $show->field('sales_initial');
            $show->field('sales_actual');
            $show->field('delivery_id');
            $show->field('is_points_gift')->as(function ($content) {
                if ($content==1){
                    return "开启";
                }else{
                    return "关闭";
                }

            });
            $show->field('is_points_discount')->as(function ($content) {
                if ($content==1){
                    return "开启";
                }else{
                    return "关闭";
                }

            });
            $show->field('is_alone_points_discount');
            $show->field('points_discount_config');
            $show->field('is_enable_grade');
            $show->field('is_alone_grade');
            $show->field('alone_grade_equity');
            $show->field('status')->as(function ($content) {
                if ($content==1){
                    return "上架";
                }else{
                    return "下架";
                }

            });
            $show->field('sort');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new GrGood(), function (Form $form) {

            $form->tab('基本信息', function (Form $form) {
                $form->text('goods_name', '商品名称')->required()->maxLength(20);
                $form->select('goods_type_id', '商品分类')->options($this->type)->required();
                $form->multipleImage('goods_img', '商品相册')->move('goodsImg')->autoUpload()->limit(5)->accept('jpg,png,gif,jpeg')->uniqueName()->saving(function ($paths) {
                    // 也可以转化为json
                    return json_encode($paths);
                });
                $form->switch('status', '状态')->default(1)
                    ->customFormat(function ($v) {
                        return $v == '1' ? 1 : 0;
                    })
                    ->saving(function ($v) {
                        return $v ? '1' : '0';
                    });
                $form->text('goods_no');
                $form->text('sort');
            });
            $form->tab('商品详情', function (Form $form) {
                $form->editor('content')->required();
            });
            $form->tab('其他设置', function (Form $form) {
                $form->image('goods_img_cover', '商品封面')->accept('jpg,png,gif,jpeg')->saveFullUrl()->uniqueName()->autoUpload()->move('goodsImg');
                $form->file('goods_video', '视频介绍')->uniqueName()->maxSize(10240)->move('goodsVideo');
                $form->text('sales_initial')->required();
                $form->text('selling_point')->required();
                $form->radio('is_points_gift', '积分赠送')->options([1 => '开启', 0 => '关闭'])->default(1);
                $form->radio('is_points_discount', '积分抵扣')->options([1 => '开启', 0 => '关闭'])->default(1);
            });
            $form->tab('规格/库存', function (Form $form) {
                $form->radio('spec_type')->when(1, function (Form $form) {
                    $form->currency('goods_now_price', '现价')->symbol('￥')->width(4)->default(1)->required();
                    $form->currency('line_price', '划线价格')->symbol('￥')->width(4);
                    $form->number('stock_total')->required();
                })
                    ->when(2, function (Form $form) {
                        $skuParams = [
                            [
                                'name' => '划线价格', // table 第一行 title
                                'field' => 'line_price', // input 的 field_name 名称
                                'default' => '', // 默认值
                            ],
                            [
                                'name' => '商品重量', // table 第一行 title
                                'field' => 'goods_weight', // input 的 field_name 名称
                                'default' => '', // 默认值
                            ],
                            [
                                'name' => 'SKU编码', // table 第一行 title
                                'field' => 'goods_sku_no', // input 的 field_name 名称
                                'default' => '', // 默认值
                            ],
                            // 扩展第二列
                        ];
                        // 编辑时
                        $skuData = []; // 数据结构见附录
                        $skuString = json_encode($skuData);
                        $form->sku('sku', '商品规格')->addColumn($skuParams)->value($skuString);

                    })
                    ->options([
                        1 => '单规格',
                        2 => '多规格',
                    ])
                    ->default(1);
            });

            // 获取提交的数据.
            $form->saving(function (Form $form) {
                // 获取表单提交数据
                $data = $form->input();
                // 百度智能云审核商品图片
                if (!empty($data['goods_img_cover'])){
                    $res=(new ReviewImages())->verify(env('IMG_URL').$data['goods_img_cover']);
                    if ($res=='不合规'){
                        $disk = Storage::disk('qiniu');
                        $disk->delete($data['goods_img_cover']);
                        return $form->response()->error('商品封面不合规，请删除重新上传~');
                    }
                }
                    // 判断是多规格值是否为空
                    if (!empty($data['sku'])){
                        // 获取规格信息
                        $sku = $data['sku'];
                        // 商品表中没有规格字段  所以取消上传此字段
                        $form->deleteInput('sku');
                        // 雪花算法 生成商品编号
                        $snowflake = new \Godruoyi\Snowflake\Snowflake;
                        $goodsNO = $snowflake->id();
                        // 将生成编号放入字段
                        $form->goods_no = $goodsNO;
                        // 是多规格
                        if ($data['spec_type'] == 2) {
                            // 拿到SKU数据，按照业务逻辑做响应处理即可。
                            $skuInfo = json_decode($sku, true);
                            $spec = array_keys($skuInfo['attrs']);
                            // 将规格信息放入缓存中
                            Redis::hset('skuInfo', $goodsNO . 'sku', $sku);
                            foreach ($spec as $val) {
                                // 获取自增的规格组id
                                $specId = GoodsSpec::insertGetId(['spec_name' => $val, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]);
                                // 规格值信息
                                $info = $skuInfo['attrs'][$val];
                                foreach ($info as $value) {
                                    // 规格值id
                                    $specValueId = GoodsSpecValue::insertGetId(['spec_value' => $value, 'spec_id' => $specId, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]);
                                    // 将规格组规格值id放入队列 用于获取生成关联信息
                                    Redis::lpush($goodsNO . 'specValueId', $specValueId);
                                    Redis::lpush($goodsNO . 'specId', $specId);
                                }
                            }
                        }
                    }

            });

            // 数据保存成功回调
            $form->saved(function (Form $form, $result) {
                // 判断是否是新增操作
                if ($form->isCreating()) {
                    // 获取表单提交的数据
                    $data=$form->input();
                    $data['goods_id']=$result;
                    // 将数据存入es
                    ElasticConnect::getEslasticInstance()->addOne('goods',$data);
                    // 自增ID
                    $newId = $result;
                    $goodsNo = $form->input('goods_no');
                    // 判断是否为多规格
                    if ($form->input('spec_type') == 2) {
                        // 取出商品规格信息
                        $skuInfo = json_decode(Redis::hget('skuInfo', $goodsNo . 'sku'), true);
                        foreach ($skuInfo['sku'] as $val) {
                            // 判断是否上传规格图片
                            if (!empty($val['pic'][0]['full_url'])) {
                                GoodsSku::create(['goods_id' => $newId, 'stock_num' => $val['stock'], 'goods_price' => $val['price'], 'goods_sku_img' => $val['pic'][0]['full_url'], 'goods_sku_no' => $val['goods_sku_no'], 'goods_weight' => $val['goods_weight'], 'line_price' => $val['line_price'], 'goods_props' => json_encode($val)]);
                            } else {
                                GoodsSku::create(['goods_id' => $newId, 'stock_num' => $val['stock'], 'goods_price' => $val['price'], 'goods_sku_no' => $val['goods_sku_no'], 'goods_weight' => $val['goods_weight'], 'line_price' => $val['line_price'], 'goods_props' => json_encode($val)]);
                            }
                        }
                        // 判断缓存中是否有对应的规格值id信息
                        while (Redis::llen($goodsNo . 'specId') != 0 && Redis::llen($goodsNo . 'specValueId') != 0) {
                            // 生成关联信息
                            GoodsSpecRel::create(['goods_id' => $newId, 'spec_id' => Redis::rpop($goodsNo . 'specId'), 'spec_value_id' => Redis::rpop($goodsNo . 'specValueId')]);
                        }
                    }
                    if (!$newId) {
                        return $form->error('数据保存失败');
                    }
                }

            });

            // 删除前回调
            $form->deleting(function (Form $form) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
                foreach ($data as $val){
                    if ($val['status']==1){
                        return $form->response()->error('上架商品不能删除');
                    }
                }
            });



            // 执行删除后回调
            $form->deleted(function (Form $form) {
                try {
                    // 开启事务
                    DB::beginTransaction();
                    // 获取待删除行数据，这里获取的是一个二维数组
                    $data = $form->model()->toArray();
                    foreach ($data as $val) {
                        // 判断是否彻底删除
                        if (!empty($val['deleted_at'])) {
                            // 删除es中数据
                            ElasticConnect::getEslasticInstance()->delData('goods',$val['goods_id']);
                            // 删除规格数据
                            GoodsSku::where('goods_id', $val['goods_id'])->delete();
                            // 获取规格组id
                            $specId = GoodsSpecRel::where('goods_id',$val['goods_id'])->select('spec_id')->get()->toArray();
                            $id=[];
                            // 规格值id
                            foreach ($specId as $k=>$v){
                                $id[$k]=$v['spec_id'];
                            }
                            // 去重规格值id
                            $arr=array_unique($id);
                            foreach ($arr as $value){
                                // 删除规格值id
                                GoodsSpecValue::where('spec_id',$value)->delete();
                                // 删除规格组id
                                GoodsSpec::where('spec_id',$value)->delete();
                                // 删除规格值和规格组关联信息
                                GoodsSpecRel::where('spec_id',$value)->delete();
                            }
                        }
                    }
                    // 事务提交
                    DB::commit();
                }catch (\Exception $exception){
                    // 回滚事务
                    DB::rollBack();
                }
                // 返回删除成功提醒，此处跳转参数无效
                return $form->response()->success('删除成功');
            });


        });
    }
}
